<template>
	<div class="container">
		<div style="position:absolute; right: 20px;">
			<a-button style="margin-left: 10px;" @click="printElement('shangtong-info-page')">打印/导出PDF</a-button>
			<a-button style="margin-left: 10px;" @click="closeTab('/shangtong')">
				<close-outlined />关闭
			</a-button>
		</div>
		<div id="shangtong-info-page">
			<a-form :model="info">
				<a-descriptions title="查看商砼预约" bordered size="middle">
					<a-descriptions-item label="项目名称">{{ info.project?.name }}</a-descriptions-item>
					<a-descriptions-item label="工号">
						<a-tree-select v-model:value="info.use_position" :dropdown-match-select-width="false" :show-search="true" placeholder="请选择工号" allow-clear tree-default-expand-all :tree-data="gonghaoTree" tree-node-filter-prop="label" style="width:100%" disabled>
							<template #title="{ label }">{{ label }}</template>
						</a-tree-select>
					</a-descriptions-item>
					<a-descriptions-item label="砼标号（类别）">{{ info.type }}</a-descriptions-item>
					<a-descriptions-item label="预计浇筑部位">{{ info.expected_location }}</a-descriptions-item>
					<a-descriptions-item label="预计浇筑方量（m3）">{{ info.fangliang }}</a-descriptions-item>
					<a-descriptions-item label="合同余量">{{ info.pendingQuantity || 0 }}</a-descriptions-item>
					<a-descriptions-item label="是否泵送（长度）">{{ info.changdu }}</a-descriptions-item>
					<a-descriptions-item label="申请塌落度（mm）">{{ info.luodu }}</a-descriptions-item>
					<a-descriptions-item label="预计浇筑日期">{{ info.add_time }}</a-descriptions-item>
					<a-descriptions-item label="现场联系人">{{ info.contacts }}</a-descriptions-item>
					<a-descriptions-item label="现场联系电话">{{ info.tel }}</a-descriptions-item>
					<a-descriptions-item label="技术指标">
						<span v-for="(item, index) in info.art_indexes" :key="index" class="mr-5">
							{{ artIndexesGongHaos.find(i => i.value === item.gonghao_id)?.label }}
						</span>
					</a-descriptions-item>
					<a-descriptions-item label="备注">{{ info.memo }}</a-descriptions-item>
				</a-descriptions>
			</a-form>
		</div>
		<h2 style="margin: 12px;">预约的发起申请人</h2>
		<a-workflow v-if="info.id" v-model:status="info.workflow_status" module="shangtong" :target-id="info.id" :project-id="info.project_id" :code="info.code" :user-id="info.apply_id" :extra="true" :steps="true" @submit="(e) => console.log(e)"></a-workflow>
		<a-form>
			<a-row :gutter="20">
				<a-col :span="24" class="py-4 text-center">
					<a-space>
						<a-button @click="closeTab('/shangtong')">
							<close-outlined />关闭
						</a-button>
					</a-space>
				</a-col>
			</a-row>
		</a-form>
	</div>
</template>

<script setup>
import { ref, computed, onMounted, getCurrentInstance, inject } from "vue";
import { post, postJson, treeToList } from "../utils";
import { useRoute } from "vue-router";
import { CloseOutlined } from "@ant-design/icons-vue";
const route = useRoute();
const id = computed(() => {
	return route.params.id || 0;
});
import dayjs from "dayjs";
import { printElement } from "@/utils/exportData.js";
import { add, subtract } from "@/utils/operation.js";
import { AWorkflow } from "@/components/index.js";
const { proxy } = getCurrentInstance();
const info = ref({})
const gonghaoTree = ref([]);
const modelOptions = ref([]);
const contractlist = ref([]);
const contractInfo = ref({});
const optType = ref(3); // 1新增 2编辑 3查看
const artIndexesGongHaos = ref([]);
post("dictionary", { root_id: 1069 }).then((data) => {
	artIndexesGongHaos.value = data.map(d => {
		return {
			value: d.id,
			label: d.name
		};
	});
});
const getPendingQuantity = async record => {
	const materialId = record.material_id || record.type;
	if (materialId) {
		record.pendingQuantity = contractInfo.value[materialId].pending_quantity;
	}
};

const changeProject = project_id => {
	const getDepartmentTree = () => {
		return new Promise((resolve, reject) => {
			// 更新工号下拉
			post("department/getTrees", { type: 4, parent_id: project_id }).then(data => {
				gonghaoTree.value = data;
				const gonghaoList = treeToList(JSON.parse(JSON.stringify(data)), []);
				if (!info.value.use_position && (info.value.gonghao_id || info.value.part)) {
					const use_position = gonghaoList.filter(i => {
						return i.id === (info.value.part || info.value.gonghao_id);
					})[0];
					info.value.use_position = use_position.value;
				} else {
					info.value.use_position = null;
					info.value.gonghao_id = null;
					info.value.part = null;
				}
				resolve();
			});
		});
	};
	const getContractAll = () => {
		return new Promise((resolve, reject) => {
			// 主要材料/混凝土专项合同
			postJson("contract/apply", { project_id: project_id, types: [1], material_types: [2] }).then(data => {
				modelOptions.value = [];
				contractlist.value = [];
				contractInfo.value = {};

				if (!data.length) {
					proxy.$message.error("当前项目尚未绑定合同");
					resolve();
				}

				contractlist.value = data;
				// 按照物资维度统计
				const materials = data
					.map(item => item.materials)
					.reduce((res, curr) => {
						res.push(...curr);
						return res;
					}, []);
				contractInfo.value = materials.reduce((res, curr) => {
					if (!res[curr.id]) {
						res[curr.id] = {
							model: curr.attr ? `${curr.model}（${curr.attr}）` : curr.model,
							pending_quantity: 0
						};
					}
					res[curr.id].pending_quantity = add([curr.ContractMaterial?.pending_quantity, res[curr.id].pending_quantity]);
					return res;
				}, {});
				modelOptions.value = Object.keys(contractInfo.value).map(key => {
					return {
						model: contractInfo.value[key].model,
						id: key
					};
				});

				// 编辑初始化处理
				if (optType.value === 2) {
					const type = info.value.type;
					const target = Object.keys(contractInfo.value).find(key => contractInfo.value[key].model === type);
					info.value.type = target || undefined;
				}
				resolve();
			});
		});
	};
	return Promise.all([getDepartmentTree(), getContractAll()]);
};
onMounted(() => {
	post("shangtong/info", { id: id.value }).then(async data => {
		data.add_time = dayjs(data.add_time).format("YYYY-MM-DD HH:mm:ss");
		info.value = data;
		if (info.value.art_indexes) {
			info.value.art_indexes = JSON.parse(info.value.art_indexes);
		}
		await changeProject(data.project_id)
		await getPendingQuantity(info.value);
	});
})


const closeTab = inject("closeTab");
</script>

<style scoped lang="scss">
.container {
	background: #fff;
	padding: 20px;
}
:deep(.ant-descriptions-title) {
  text-align: center;
}
</style>
